package com.bdzl.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdzl.biz.dao.OrderDao;
import com.bdzl.biz.service.*;
import com.bdzl.biz.servicefeign.AdminFeignService;
import com.bdzl.biz.servicefeign.AuthFeignService;
import com.bdzl.biz.servicefeign.FlowFeignService;
import com.bdzl.pub.config.Constant;
import com.bdzl.pub.entity.data.UserInfoDO;
import com.bdzl.pub.entity.flow.ActChkRecDO;
import com.bdzl.pub.entity.flow.ActNodeNextDO;
import com.bdzl.pub.entity.loan.*;
import com.bdzl.pub.entity.sys.UserDO;
import com.bdzl.pub.string.StringUtils;
import com.bdzl.pub.util.file.PdfUtil;
import com.bdzl.pub.util.param.R;
import com.bdzl.pub.vo.data.UserInfoVO;
import com.bdzl.pub.vo.flow.ActNodeVO;
import com.bdzl.pub.vo.loan.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private AdminFeignService adminFeignService;
	@Autowired
	private AuthFeignService authFeignService;
	@Autowired
	private OrderRelService orderRelService;
	@Autowired
	private FlowFeignService flowFeignService;
	@Autowired
	private OrderCustService orderCustService;
	@Autowired
	private OrderUsevehService orderUsevehService;
	@Autowired
	private OrderCallService orderCallService;
	@Autowired
	private OrderVisitorService orderVisitorService;
	@Autowired
	private OdrFileCategoryService odrFileCategoryService;
	@Autowired
	private OrderVehService orderVehService;
	@Autowired
	private OrderMailService orderMailService;
	@Autowired
	private OrderMailFileService orderMailFileService;



	@Override
	public OrderDO get(String odrNo){
		return orderDao.get(odrNo);
	}

	@Override
	public List<OrderDO> list(Map<String, Object> map){
		return orderDao.list(map);
	}

	@Override
	public int count(Map<String, Object> map){
		return orderDao.count(map);
	}

	@Override
	public int save(OrderDO order){
		return orderDao.save(order);
	}

	@Override
	public int update(OrderDO order){
		return orderDao.update(order);
	}

	@Override
	public int remove(String odrNo){
		return orderDao.remove(odrNo);
	}

	@Override
	public int batchRemove(String[] odrNos){
		return orderDao.batchRemove(odrNos);
	}

	@Override
	@Transactional
	public R newspaper(UserInfoVO[] userInfoVOs,Integer userId) {
		int save = 0;
		//生成订单号
		String orderIdByUUId = StringUtils.getOrderIdByUUId();
		//客户编号
		Integer clientId = null;
		//配偶身份证
		String idCard = null;
		//校验通过的数据
		List<UserInfoVO> userInfoVOListOk = new ArrayList<>();
		//判断是否有重复身份证号
		List<String> idCardList = new ArrayList<>();
		for (UserInfoVO userInfoVO : userInfoVOs) {
			idCardList.add(userInfoVO.getConCardid());
		}
		Set<String> set= new HashSet<>(idCardList);
		boolean idCardresult= idCardList.size() == set.size();
		if(!idCardresult) {
		//身份证号重复
			return R.error("身份证号重复，请核对！");
		}
		//判断是否有重复手机号
		List<String> phoneList = new ArrayList<>();
		for (UserInfoVO userInfoVO : userInfoVOs) {
			phoneList.add(userInfoVO.getConMobile());
		}
		Set<String> setPhone= new HashSet<>(phoneList);
		boolean phoneResult= phoneList.size() == setPhone.size();
		if(!phoneResult) {
			//手机号重复
			return R.error("手机号重复，请核对！");
		}

		for (UserInfoVO userInfoVO : userInfoVOs) {
			//校验手机号
			Object checkPhoneCode = authFeignService.checkPhoneCode(userInfoVO.getConMobile(), userInfoVO.getVerificationCode());
			HashMap result = (HashMap) checkPhoneCode;
			if ("0002".equals(result.get("respCode"))){
				return R.error("手机号："+userInfoVO.getConMobile()+"，验证码错误！");
			}
			if (userInfoVO.getType()==1){
				idCard = userInfoVO.getConCardid();
			}
			userInfoVOListOk.add(userInfoVO);
		}

		for (UserInfoVO userInfoVO : userInfoVOListOk) {
			//添加客户信息到数据库
			//写入客户配偶身份证号，获取客户编号
			if (userInfoVO.getType()==0){
				userInfoVO.setConSpouse(idCard);
			}
			userInfoVO.setConCreuser(userId);
			userInfoVO.setConCretime(new Date());
			Object saveUserInfo = adminFeignService.saveUserInfo(userInfoVO);
			HashMap result = (HashMap) saveUserInfo;
			System.out.println("------------------"+result);
			if (userInfoVO.getType()==0){
				clientId = (Integer) result.get("data");
			}
			userInfoVO.setConId((Integer) result.get("data"));
		}
		//添加担保人数据
		for (UserInfoVO userInfoVO : userInfoVOListOk) {
			//判断是否为担保人
			if (userInfoVO.getType()==2){
				OrderRelDO orderRelDO = new OrderRelDO();
				orderRelDO.setRelOdrNo(orderIdByUUId);
				orderRelDO.setRelCustUser(clientId);
				orderRelDO.setRelType("Guarantee");
				orderRelDO.setRelName(userInfoVO.getConName());
				orderRelDO.setRelPhone(userInfoVO.getConMobile());
				orderRelDO.setRelCardid(String.valueOf(userInfoVO.getConId()));
				orderRelService.save(orderRelDO);
			}
		}
		OrderDO orderDO = new OrderDO();
		orderDO.setOdrOrg("1");
		orderDO.setOdrNo(orderIdByUUId);
		orderDO.setOdrType("Lease");
		orderDO.setOdrCust(clientId);
		orderDO.setOdrBizType("中车");
		orderDO.setOdrState("Y000");
		orderDO.setOdrReturnStatus(0);
		orderDO.setOdrCreator(userId);
		orderDO.setOdrCretime(new Date());
		//获取后台用户数据
		Object userById = authFeignService.getUserById(userId);
//		UserDO userDO = (UserDO) userById;
		// 将数据转成json字符串
		String jsonObject= JSON.toJSONString(userById);
		//将json转成需要的对象
		UserDO userDO= JSONObject.parseObject(jsonObject,UserDO.class);
		orderDO.setOdrSalesman(userDO.getUserNickname());
		//创建审核记录
		List<ActNodeVO> actNodeVOList = flowFeignService.getNode("001");
		if (actNodeVOList!=null && actNodeVOList.size()>2){
			ActChkRecDO actChkRecDO = new ActChkRecDO();
			actChkRecDO.setAcrOdr(orderIdByUUId);
			actChkRecDO.setAcrNodeId(actNodeVOList.get(0).getNodeId());
			actChkRecDO.setAcrCurrentNode(actNodeVOList.get(0).getNodeTitle());
			actChkRecDO.setAcrOperator(Integer.valueOf(actNodeVOList.get(0).getNodeUserVal()));
			actChkRecDO.setAcrBeginTime(new Date());
			actChkRecDO.setAcrEndTime(new Date());
			actChkRecDO.setAcrChkFlag("N");
			flowFeignService.saveActChkRec(actChkRecDO);
			//流程电子授权书
			ActChkRecDO actChkRecDOs = new ActChkRecDO();
			actChkRecDOs.setAcrOdr(orderIdByUUId);
			actChkRecDOs.setAcrNodeId(actNodeVOList.get(1).getNodeId());
			actChkRecDOs.setAcrCurrentNode(actNodeVOList.get(1).getNodeTitle());
			actChkRecDOs.setAcrOperator(Integer.valueOf(actNodeVOList.get(1).getNodeUserVal()));
			actChkRecDOs.setAcrBeginTime(new Date());
			actChkRecDOs.setAcrChkFlag("N");
			flowFeignService.saveActChkRec(actChkRecDOs);
		}else {
			return R.error("请先创建工作流！");
		}
		save = this.save(orderDO);
		if(save>0){
			return R.ok();
		}
		return R.error();
	}

	@Override
	public List<OrderVO> checkList(Map<String,Object> map) {
		return orderDao.checkList(map);
	}

	@Override
	public List<OrderVO> processedList(Map<String, Object> map) {
		return orderDao.processedList(map);
	}

	@Override
	public List<OrderVO> newsletterList(Map<String, Object> map) {
		List<OrderVO> orderVOList = orderDao.newsletterList(map);

		if (orderVOList!=null&&orderVOList.size()>0){
			for (OrderVO orderVO : orderVOList) {
				StringBuilder modelInformation= null;
				if (orderVO.getVehBrand()!=null){
					modelInformation = new StringBuilder(orderVO.getVehBrand());
				}
				if (orderVO.getVehModel()!=null){
					assert modelInformation != null;
					modelInformation.append(orderVO.getVehModel());
				}
				orderVO.setModelInformation(String.valueOf(modelInformation));
			}
		}
		return orderVOList;
	}

	@Override
	public OrderVO additionalMaterials(String odrNo) {
		OrderVO orderVO = orderDao.additionalMaterials(odrNo);
		if (orderVO.getOrderVehDO()==null){
			orderVO.setOrderVehDO(new OrderVehDO());
		}
		List<OrderPayAccountDO> orderPayAccountDOList = orderVO.getOrderPayAccountDOList();
		if (orderPayAccountDOList.size()==0){
			orderPayAccountDOList.add(new OrderPayAccountDO());
		}
		orderVO.setOdrZeroFlag("Y");
		//判断申请人是否已填
		UserInfoVO applicant = this.applicant(orderVO.getConCardId());
		if (applicant!=null){
			if (applicant.getConSon() == null || applicant.getConMonthIn() == null || applicant.getConMonthOut() == null ||  applicant.getConLiveType() == null
					||applicant.getConComName()==null||applicant.getConTranFlag()==null||applicant.getConSupplyType()==null||applicant.getConTranYear()==null) {
				orderVO.setApplicantType(false);
			}
			//融资租赁订单客户信息表
			OrderCustDO orderCustDO = applicant.getOrderCustDO();
			if (orderCustDO!=null) {
				if ( orderCustDO.getCustDriverType() == null|| orderCustDO.getCustLiabilities() == null  || orderCustDO.getCustUseFlag() == null) {
					orderVO.setApplicantType(false);
				}
			}else {
				orderVO.setApplicantType(false);
			}
			if ("已婚".equals(applicant.getConMarriage())){
				//获取配偶数据
				UserInfoDO spouse = applicant.getSpouse();
				if (spouse!=null){
					if (spouse.getConName()==null||spouse.getConSex()==null||spouse.getConCardid()==null
							||spouse.getConMobile()==null||spouse.getConComName()==null||spouse.getConPost()==null){
						orderVO.setApplicantType(false);
					}
				}else {
					orderVO.setApplicantType(false);
				}
			}
		}

		//判断实际用车人是否已填
		UserInfoVO userInfoVO = this.actualUser(orderVO.getConCardId(), odrNo);
		if (userInfoVO!=null){
			if (userInfoVO.getConMobile()==null||userInfoVO.getConSon()==null||userInfoVO.getConMarriage()==null||
					userInfoVO.getConAdr()==null||userInfoVO.getConTranFlag()==null||userInfoVO.getConWorkYear()==null
					||userInfoVO.getConTranYear()==null||userInfoVO.getConComName()==null){
				orderVO.setActualUserType(false);
			}
		}else {
			orderVO.setActualUserType(false);
		}

		//获取实际用车人不为申请人的数据
		OrderUsevehDO orderUsevehDO = userInfoVO.getOrderUsevehDO();
		if (orderUsevehDO!=null){
			if (orderUsevehDO.getUvGuaranteeFlag()==null||orderUsevehDO.getUvReason()==null||orderUsevehDO.getUvLiabilities()==null){
				orderVO.setActualUserType(false);
			}
		}else {
			orderVO.setActualUserType(false);
		}


		//判断担保人是否已填
		List<UserInfoVO> guarantor = this.guarantor(odrNo, orderVO.getOdrCust());
		if (guarantor.size()>0){
			for (UserInfoVO infoVO : guarantor) {
				if (infoVO.getConCardPeople()==null||infoVO.getConCardEmblem()==null||infoVO.getConName()==null||infoVO.getConSex()==null||
						infoVO.getConBirth()==null||infoVO.getConCardid()==null||infoVO.getConCardAdr()==null||infoVO.getConMobile()==null
						||infoVO.getConMonthIn()==null){
					orderVO.setGuarantorType(false);
				}
				//获取担保人与申请人相关信息
				OrderRelDO orderRelDO = infoVO.getOrderRelDO();
				if (orderRelDO!=null){
					if (orderRelDO.getRelRelation()==null||orderRelDO.getRelJob()==null){
						orderVO.setGuarantorType(false);
					}
				}

			}
		}else {
			orderVO.setGuarantorType(false);
		}
		//判断联系人是否已填
		List<OrderRelDO> contact = this.contactPerson(odrNo, userInfoVO.getOdrCust(), "Contact");
		if (contact.size()>0){
			for (OrderRelDO orderRelDO : contact) {
				if (orderRelDO.getRelName()==null||orderRelDO.getRelRelation()==null||orderRelDO.getRelPhone()==null){
					orderVO.setContactPersonType(false);
				}
			}
		}else {
			orderVO.setContactPersonType(false);
		}
		//判断挂靠单位是否已填
		OrderCallDO orderCallDO = this.callCompany(odrNo);
		if (orderCallDO!=null){
			if (orderCallDO.getCallComName()==null||orderCallDO.getCallCredate()==null||orderCallDO.getCallLegal()==null||orderCallDO.getCallLegalPhone()==null||orderCallDO.getCallRoadTransport()==null){
				orderVO.setAffiliatedUnitType(false);
			}
		}else {
			orderVO.setAffiliatedUnitType(false);
		}

		return orderVO;
	}


	@Override
	public UserInfoVO applicant(String conCardId) {
		UserInfoVO applicant = orderDao.applicant(conCardId);
		if (applicant.getOrderCustDO()==null){
			applicant.setOrderCustDO(new OrderCustDO());
		}
		return applicant;
	}

	@Override
	public R saveApplicant(UserInfoVO userInfoVO, UserDO userDO) {

		//融资租赁订单客户信息表
		OrderCustDO orderCustDO = userInfoVO.getOrderCustDO();
		if (orderCustDO!=null){
			if (userInfoVO.getConSon()==null||userInfoVO.getConMonthIn()==null||userInfoVO.getConMonthOut()==null||orderCustDO.getCustDriverType()==null
			||orderCustDO.getCustLiabilities()==null||userInfoVO.getConLiveType()==null||orderCustDO.getCustUseFlag()==null||userInfoVO.getConTranFlag()==null
			||userInfoVO.getConSupplyType()==null||userInfoVO.getConTranYear()==null||userInfoVO.getConComName()==null){
				return R.error("请补充申请人信息！");
			}

			if (orderCustDO.getCustId()!=null && !"".equals(orderCustDO.getCustId())){
				orderCustDO.setCustOdrNo(userInfoVO.getOdrNo());
				orderCustDO.setCustCardId(String.valueOf(userInfoVO.getConId()));
				orderCustDO.setCustModuser(userDO.getUserId());
				orderCustDO.setCustModtime(new Date());
				orderCustService.update(orderCustDO);
			}else {
				orderCustDO.setCustOdrNo(userInfoVO.getOdrNo());
				orderCustDO.setCustCardId(String.valueOf(userInfoVO.getConId()));
				orderCustDO.setCustCreator(userDO.getUserId());
				orderCustDO.setCustCretime(new Date());
				orderCustService.save(orderCustDO);
			}
		}

		if ("已婚".equals(userInfoVO.getConMarriage())){
			//获取配偶数据
			UserInfoDO spouse = userInfoVO.getSpouse();
			if (spouse==null||spouse.getConName()==null||spouse.getConSex()==null||spouse.getConCardid()==null
			||spouse.getConMobile()==null||spouse.getConComName()==null||spouse.getConPost()==null){
				return R.error("请补充配偶信息！");
			}
			//更新配偶信息
			spouse.setConModuser(userDO.getUserId());
			spouse.setConModtime(new Date());
			adminFeignService.updateUserInfo(spouse);
		}

		//更新客户信息
		userInfoVO.setConModuser(userDO.getUserId());
		userInfoVO.setConModtime(new Date());
		adminFeignService.updateUserInfo(userInfoVO);

		return R.ok();
	}

	@Override
	public OrderCallDO callCompany(String odrNo) {
		OrderCallDO orderCallDO = orderDao.callCompany(odrNo);
		if (orderCallDO==null){
			return new OrderCallDO();
		}
		return orderCallDO;
	}


	@Override
	public UserDO getUserInfo(HttpServletRequest request){
		String accessToken = request.getHeader("X-Access-Token");
		Object user = authFeignService.getUser(accessToken);
		// 将数据转成json字符串
		String jsonObject= JSON.toJSONString(user);
		//将json转成需要的对象
		return JSONObject.parseObject(jsonObject,UserDO.class);
	}

	@Override
	public UserInfoVO actualUser(String custCardId,String odrNo) {
		//根据身份证查询是否为实际用车人
		OrderCustDO orderCustDO = orderCustService.getByCustCardId(custCardId);
		UserInfoVO userInfo = new UserInfoVO();
		if (orderCustDO!=null){
			//为实际用车人
			if ("Y".equals(orderCustDO.getCustUseFlag())){
				userInfo = adminFeignService.getUserInfo(Integer.valueOf(custCardId), "-1");
				userInfo.setOrderCustDO(orderCustDO);
				//不为实际用车人
			}else if ("N".equals(orderCustDO.getCustUseFlag())){
				//查询实际用车人表
				OrderUsevehDO usevehDO = orderUsevehService.getByUvOdr(odrNo);
				if (usevehDO!=null){
					userInfo = adminFeignService.getUserInfo(Integer.valueOf(usevehDO.getUvCardId()), "-1");
					userInfo.setOrderUsevehDO(usevehDO);
				}else {
					userInfo.setOrderUsevehDO(new OrderUsevehDO());
				}
			}
			return userInfo;
		}else {
			return new UserInfoVO();
		}
	}

	@Override
	public List<OrderRelDO> contactPerson(String relOdrNo, Integer relCustUser,String relType) {
		List<OrderRelDO> orderRelDOList = orderDao.contactPerson(relOdrNo, relCustUser, relType);
		if (orderRelDOList.size()<=0){
			orderRelDOList.add(new OrderRelDO());
		}
		return orderRelDOList;
	}

	@Override
	public void saveContactPerson(OrderRelDO orderRelDO) {
		if (orderRelDO.getRelId()!=null){
			orderRelService.update(orderRelDO);
		}else {
			orderRelService.save(orderRelDO);
		}
	}

	@Override
	public R saveActualUser(UserInfoVO userInfoVO,UserDO userDO) {
		if ("Y".equals(userInfoVO.getCustUseFlag())){
			if (userInfoVO.getConWorkYear()==null){
				return R.error("请补充实际用车人信息！");
			}
			//更新客户数据
			adminFeignService.updateUserInfo(userInfoVO);
			//获取融资租赁订单客户信息
			OrderCustDO orderCustDO = userInfoVO.getOrderCustDO();
			if (orderCustDO.getCustId()!=null){
				orderCustDO.setCustOdrNo(userInfoVO.getOdrNo());
				orderCustDO.setCustModuser(userDO.getUserId());
				orderCustDO.setCustModtime(new Date());
				orderCustService.update(orderCustDO);
			}else {
				orderCustDO.setCustCardId(String.valueOf(userInfoVO.getConId()));
				orderCustDO.setCustOdrNo(userInfoVO.getOdrNo());
				orderCustDO.setCustUseFlag("Y");
				orderCustDO.setCustCreator(userDO.getUserId());
				orderCustDO.setCustCretime(new Date());
				orderCustService.save(orderCustDO);
			}
			return R.ok();
		}else if ("N".equals(userInfoVO.getCustUseFlag())){
			if (userInfoVO.getConMobile()==null||userInfoVO.getConSon()==null||userInfoVO.getConMarriage()==null||
					userInfoVO.getConAdr()==null||userInfoVO.getConTranFlag()==null||userInfoVO.getConWorkYear()==null
					||userInfoVO.getConTranYear()==null||userInfoVO.getConComName()==null){
				return R.error("请补充实际用车人信息！");
			}
			//获取实际用车人不为申请人的数据
			OrderUsevehDO orderUsevehDO = userInfoVO.getOrderUsevehDO();
			if (orderUsevehDO.getUvGuaranteeFlag()==null||orderUsevehDO.getUvReason()==null||orderUsevehDO.getUvLiabilities()==null){
				return R.error("请补充实际用车人信息！");
			}
			UserInfoDO userInfoDO = adminFeignService.getSpouse(userInfoVO.getConCardid());
			if (userInfoDO!=null){
				userInfoVO.setConId(userInfoDO.getConId());
				//更新客户数据表
				adminFeignService.updateUserInfo(userInfoVO);
				Integer orderRelId = orderRelService.getOrderRel(orderUsevehDO.getUvOdr(), userInfoVO.getOdrCust(), userInfoDO.getConId());
				if (orderRelId!=null){
					//更新担保人信息
					OrderRelDO orderRelDO = new OrderRelDO();
					orderRelDO.setRelId(orderRelId);
					orderRelDO.setRelOdrNo(orderUsevehDO.getUvOdr());
					orderRelDO.setRelCustUser(userInfoVO.getOdrCust());
					orderRelDO.setRelType("Guarantee");
					orderRelDO.setRelName(userInfoVO.getConName());
					orderRelDO.setRelPhone(userInfoVO.getConMobile());
					orderRelDO.setRelCardid(String.valueOf(userInfoDO.getConId()));
					orderRelService.update(orderRelDO);
				}else {
					if ("Y".equals(orderUsevehDO.getUvGuaranteeFlag())){
						//添加担保人信息
						OrderRelDO orderRelDO = new OrderRelDO();
						orderRelDO.setRelOdrNo(orderUsevehDO.getUvOdr());
						orderRelDO.setRelCustUser(userInfoVO.getOdrCust());
						orderRelDO.setRelType("Guarantee");
						orderRelDO.setRelName(userInfoVO.getConName());
						orderRelDO.setRelPhone(userInfoVO.getConMobile());
						orderRelDO.setRelCardid(String.valueOf(userInfoDO.getConId()));
						orderRelService.save(orderRelDO);
					}
				}

				//添加融资租赁订单实际用车人信息表
				if (orderUsevehDO.getUvId()!=null){
					orderUsevehDO.setUvCardId(String.valueOf(userInfoDO.getConId()));
//					orderUsevehDO.setUvOdr(userInfoVO.getOdrNo());
					orderUsevehDO.setCustModuser(userDO.getUserId());
					orderUsevehDO.setCustModtime(new Date());
					orderUsevehService.update(orderUsevehDO);
				}else {
					orderUsevehDO.setUvCardId(String.valueOf(userInfoDO.getConId()));
//					orderUsevehDO.setUvOdr(userInfoVO.getOdrNo());
					orderUsevehDO.setUvCreator(userDO.getUserId());
					orderUsevehDO.setUvCretime(new Date());
					orderUsevehService.save(orderUsevehDO);
				}
			}else {
				//添加担保人客户信息数据
				Object userInfo = adminFeignService.saveUserInfo(userInfoVO);
				HashMap result = (HashMap) userInfo;
				System.out.println("------------------"+result);
				Integer clientId = (Integer) result.get("data");
				if ("Y".equals(orderUsevehDO.getUvGuaranteeFlag())){
					OrderRelDO orderRelDO = new OrderRelDO();
					orderRelDO.setRelOdrNo(orderUsevehDO.getUvOdr());
					orderRelDO.setRelCustUser(userInfoVO.getOdrCust());
					orderRelDO.setRelType("Guarantee");
					orderRelDO.setRelName(userInfoVO.getConName());
					orderRelDO.setRelPhone(userInfoVO.getConMobile());
					orderRelDO.setRelCardid(String.valueOf(clientId));
					orderRelService.save(orderRelDO);
				}
				//添加融资租赁订单实际用车人信息表
				if (orderUsevehDO.getUvId()!=null){
					orderUsevehDO.setUvCardId(String.valueOf(clientId));
//					orderUsevehDO.setUvOdr(userInfoVO.getOdrNo());
					orderUsevehDO.setCustModuser(userDO.getUserId());
					orderUsevehDO.setCustModtime(new Date());
					orderUsevehService.update(orderUsevehDO);
				}else {
					orderUsevehDO.setUvCardId(String.valueOf(clientId));
//					orderUsevehDO.setUvOdr(userInfoVO.getOdrNo());
					orderUsevehDO.setUvCreator(userDO.getUserId());
					orderUsevehDO.setUvCretime(new Date());
					orderUsevehService.save(orderUsevehDO);
				}
			}
			return R.ok();
		}
		return R.error();
	}

	@Override
	public List<UserInfoVO> guarantor(String relOdrNo, Integer relCustUser) {
		//查询担保人
		List<OrderRelDO> guarantee = this.contactPerson(relOdrNo, relCustUser, "Guarantee");
		List<UserInfoVO> userInfoVOList = new ArrayList<>();
		for (OrderRelDO orderRelDO : guarantee) {
			if (orderRelDO.getRelId()!=null){
				UserInfoVO userInfo = adminFeignService.getUserInfo(Integer.valueOf(orderRelDO.getRelCardid()), "-1");
				userInfo.setOrderRelDO(orderRelDO);
				boolean judgmentCarUser = orderUsevehService.judgmentCarUser(relOdrNo, orderRelDO.getRelCardid());
				if (judgmentCarUser){
					userInfo.setGuarantorFlag("Y");
				}
				userInfoVOList.add(userInfo);
			}
		}
		if (userInfoVOList.size()<=0){
			UserInfoVO userInfoVO = new UserInfoVO();
			userInfoVO.setOrderRelDO(new OrderRelDO());
			userInfoVOList.add(userInfoVO);
		}
		return userInfoVOList;
	}

	@Override
	public R calculationFormula(OrderVO order) {

		//厂家超额贴息（财务录入）
		BigDecimal poSubsidyFac = order.getOdrSubsidyFac();
		//息差返还（财务录入）
		BigDecimal poInstSpread = order.getOdrInstSpread();
		if (poSubsidyFac==null){
			order.setOdrSubsidyCust(new BigDecimal("0"));
		}
		if (poInstSpread==null){
			order.setOdrInstSpread(new BigDecimal("0"));
		}
		//获取车辆信息数据
		OrderVehDO orderVehDO = order.getOrderVehDO();
		//车辆数量
		Integer vehCount = orderVehDO.getVehCount();
		//底盘单价
		BigDecimal vehChassisPrice = orderVehDO.getVehChassisPrice();
		//加装总额
		BigDecimal vehAddMoney = orderVehDO.getVehAddMoney();
		//车辆单价
		orderVehDO.setVehPrice(vehChassisPrice.add(vehAddMoney).setScale(2,BigDecimal.ROUND_HALF_UP));
		BigDecimal vehPrice = orderVehDO.getVehPrice();
		//系统车辆单价
		BigDecimal vehSysPrice = orderVehDO.getVehSysPrice();
		//客户融资额(单台融资金额)
		BigDecimal odrLoanCust = order.getOdrLoanCust();
		//抵押费（单台抵押费）
		BigDecimal odrMortgageFee = order.getOdrMortgageFee();
		//融资期限
		Integer odrIssue = order.getOdrIssue();
		//客户超额贴息
		BigDecimal odrSubsidyCust = order.getOdrSubsidyCust();
		//厂家超额贴息（财务录入）
		BigDecimal odrSubsidyFac = order.getOdrSubsidyFac();
		//反利率
		BigDecimal odrReturnRate = order.getOdrReturnRate();
		//总费率
		BigDecimal odrTotalRate = order.getOdrTotalRate();
		//月息
		BigDecimal odrMonInterest = order.getOdrMonInterest();
		//奖金率
		BigDecimal odrBonusRate = order.getOdrBonusRate();
		//保底费率
		BigDecimal odrMinRate = order.getOdrMinRate();
		//利润率
		BigDecimal odrProfitRate = order.getOdrProfitRate();

		if ("N".equals(order.getOdrZeroFlag())){

			//月租金
			if (odrIssue>0){
				BigDecimal odrMonthRepay = ((odrLoanCust.add(odrMortgageFee)).multiply((odrTotalRate.add(BigDecimal.ONE))).divide(BigDecimal.valueOf(odrIssue),2,BigDecimal.ROUND_HALF_UP));
				//有小数上进个位
				double ceil = Math.ceil(odrMonthRepay.doubleValue());
				BigDecimal bigDecimal2 = BigDecimal.valueOf(ceil).multiply(BigDecimal.valueOf(vehCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
				order.setOdrMonthRepay(bigDecimal2);
			}

			//首付金额
			BigDecimal odrFirstMoney = (vehPrice.subtract(odrLoanCust)).multiply(BigDecimal.valueOf(vehCount));
			order.setOdrFirstMoney(odrFirstMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
			//首付比例
			if (vehPrice.compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrFirstRate = (vehPrice.subtract(odrLoanCust)).divide(vehPrice,4,BigDecimal.ROUND_HALF_UP).setScale(4,BigDecimal.ROUND_HALF_UP);
				order.setOdrFirstRate(odrFirstRate);
			}

			//系统融资总额
			BigDecimal odrLoanSys1 =(odrLoanCust.add(odrMortgageFee)).multiply((odrTotalRate.add(BigDecimal.ONE))).divide((BigDecimal.ONE.add(odrMinRate)),0,BigDecimal.ROUND_HALF_UP).setScale(0,BigDecimal.ROUND_DOWN);
			double floor = Math.floor(odrLoanSys1.doubleValue());
			BigDecimal bigDecimal1=BigDecimal.TEN;
			BigDecimal bigDecimal3 = BigDecimal.valueOf(floor).divide(bigDecimal1, 2,BigDecimal.ROUND_HALF_UP);
			//有上进十位
			double ceils = Math.ceil(bigDecimal3.doubleValue());
			double v = ceils * 10;
			//系统融资总额(最后准确的值)
			BigDecimal odrLoanSys2 = BigDecimal.valueOf(v).multiply(BigDecimal.valueOf(vehCount));
			BigDecimal odrLoanSys = new BigDecimal(odrLoanSys2.stripTrailingZeros().toPlainString());
			order.setOdrLoanSys(odrLoanSys.setScale(2,BigDecimal.ROUND_HALF_UP));
			//系统首付比例
			if (vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrFirstSysRate = (vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).subtract(odrLoanSys)).divide(vehSysPrice.multiply(BigDecimal.valueOf(vehCount)), 4,BigDecimal.ROUND_HALF_UP);
				order.setOdrFirstSysRate(odrFirstSysRate);
			}

			//系统首付金额
			BigDecimal odrFirstSysMoney = vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).subtract(odrLoanSys).setScale(2, BigDecimal.ROUND_HALF_UP);
			order.setOdrFirstSysMoney(odrFirstSysMoney);
			//经销商返佣
			BigDecimal odrReturnMoney = odrLoanCust.multiply(odrReturnRate).multiply(BigDecimal.valueOf(vehCount)).setScale(2,BigDecimal.ROUND_HALF_UP);
			order.setOdrReturnMoney(odrReturnMoney);
			//奖金
			BigDecimal odrBonusMoney = odrLoanCust.multiply(odrBonusRate).multiply(BigDecimal.valueOf(vehCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
			order.setOdrBonusMoney(odrBonusMoney);

			//服务费
			BigDecimal odrServiceCharge = odrLoanSys.subtract(((odrLoanCust.add(odrSubsidyCust)).multiply(BigDecimal.valueOf(vehCount))));
			//融资服务费
//			BigDecimal odrServiceCharge = odrServiceCharges;
			if (order.getOdrPayItem()!=null && !"null".equals(order.getOdrPayItem())){
				for (String poPayFalg : order.getOdrPayItem().split(",")) {
					//类型存在返佣
					if ("comm".equals(poPayFalg)){
						odrServiceCharge = odrServiceCharge.subtract(odrReturnMoney);
					}else if ("rebate".equals(poPayFalg)){//存在奖金
						odrServiceCharge = odrServiceCharge.subtract(odrBonusMoney);
					}/*else if ("carpay".equals(poPayFalg)){//车款
					odrServiceCharge = odrServiceCharge.subtract((order.getPoLoanCust().add(order.getPoSubsidyCust())).multiply(BigDecimal.valueOf(payOrder.getPoVehCount())));
				}*/
				}
			}
			order.setOdrServiceCharge(odrServiceCharge.setScale(2,BigDecimal.ROUND_HALF_UP));
			//打款金额
			//奖金、返佣、车款
			BigDecimal bonusAndRebate = odrLoanCust.multiply(BigDecimal.valueOf(vehCount));
			if (order.getOdrPayItem()!=null && !"null".equals(order.getOdrPayItem())){
				for (String poPayFalg : order.getOdrPayItem().split(",")) {
					//类型存在返佣
					if ("comm".equals(poPayFalg)){
						bonusAndRebate = bonusAndRebate.add(odrReturnMoney);
					}else if ("rebate".equals(poPayFalg)){//存在奖金
						bonusAndRebate = bonusAndRebate.add(odrBonusMoney);
					}/*else if ("carpay".equals(poPayFalg)){//车款
					bonusAndRebate = bonusAndRebate.add(order.getPoLoanCust().multiply(BigDecimal.valueOf(order.getPoVehCount())));
				}*/
				}
				BigDecimal odrPayMoney = bonusAndRebate;
				order.setOdrPayMoney(odrPayMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
			}

			//公司利润

			BigDecimal odrProfitMoney = odrLoanSys.subtract(odrReturnMoney).subtract(odrBonusMoney).subtract(((odrLoanCust.add(odrMortgageFee).add(odrSubsidyFac).subtract(poInstSpread)).multiply(BigDecimal.valueOf(vehCount))));
			order.setOdrProfitMoney(odrProfitMoney.setScale(2,BigDecimal.ROUND_HALF_UP));

			//毛利率
			if (odrLoanCust.multiply(BigDecimal.valueOf(vehCount)).compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrGrossRate = odrProfitMoney.divide(odrLoanCust.multiply(BigDecimal.valueOf(vehCount)), 4, BigDecimal.ROUND_HALF_UP);
				order.setOdrGrossRate(odrGrossRate.setScale(4,BigDecimal.ROUND_HALF_UP));
			}

/*
			//市场月费率（月息）
			BigDecimal poMonthRate = order.getPoTotalRate().divide(BigDecimal.valueOf(order.getPoLoanIssue()),5,BigDecimal.ROUND_HALF_UP);
			order.setPoMonthRate(poMonthRate);
			//String 市场月费率=df.format(市场月费率1);
			//月租
			double ceil1 = Math.ceil(((order.getPoLoanCust().add(order.getPoMortgageFee())).multiply((order.getPoTotalRate().add(new BigDecimal("1"))).setScale(4,BigDecimal.ROUND_DOWN)).divide(BigDecimal.valueOf(payOrder.getPoLoanIssue()), 0)).doubleValue());
			BigDecimal poMonthRepay = BigDecimal.valueOf(ceil1).multiply(BigDecimal.valueOf(order.getPoVehCount()));
			order.setPoMonthRepay(new BigDecimal(poMonthRepay.stripTrailingZeros().toPlainString()));*/


			System.out.println("计算出来的=========="+order);
			return R.ok(order);
		}else {
			//月租金
			if (odrIssue>0){
				BigDecimal odrMonthRepay = ((odrLoanCust.add(odrMortgageFee)).divide(BigDecimal.valueOf(odrIssue),2,BigDecimal.ROUND_HALF_UP));
				//有小数上进个位
				double ceil = Math.ceil(odrMonthRepay.doubleValue());
				BigDecimal bigDecimal2 = BigDecimal.valueOf(ceil).multiply(BigDecimal.valueOf(vehCount)).setScale(2, BigDecimal.ROUND_HALF_UP);
				order.setOdrMonthRepay(bigDecimal2);
			}

			//首付金额
			BigDecimal odrFirstMoney = (vehPrice.subtract(odrLoanCust)).multiply(BigDecimal.valueOf(vehCount));
			order.setOdrFirstMoney(odrFirstMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
			//首付比例
			if (vehPrice.compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrFirstRate = (vehPrice.subtract(odrLoanCust)).divide(vehPrice,4,BigDecimal.ROUND_HALF_UP).setScale(4,BigDecimal.ROUND_HALF_UP);
				order.setOdrFirstRate(odrFirstRate);
			}

			//系统融资总额
			BigDecimal odrLoanSys1 =(odrLoanCust.add(odrMortgageFee)).setScale(0,BigDecimal.ROUND_DOWN);
			double floor = Math.floor(odrLoanSys1.doubleValue());
			BigDecimal bigDecimal1=BigDecimal.TEN;
			BigDecimal bigDecimal3 = BigDecimal.valueOf(floor).divide(bigDecimal1, 2,BigDecimal.ROUND_HALF_UP);
			//有上进十位
			double ceils = Math.ceil(bigDecimal3.doubleValue());
			double v = ceils * 10;
			//系统融资总额(最后准确的值)
			BigDecimal odrLoanSys2 = BigDecimal.valueOf(v).multiply(BigDecimal.valueOf(vehCount));
			BigDecimal odrLoanSys = new BigDecimal(odrLoanSys2.stripTrailingZeros().toPlainString());
			order.setOdrLoanSys(odrLoanSys.setScale(2,BigDecimal.ROUND_HALF_UP));
			//系统首付比例
			if (vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrFirstSysRate = (vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).subtract(odrLoanSys)).divide(vehSysPrice.multiply(BigDecimal.valueOf(vehCount)), 4,BigDecimal.ROUND_HALF_UP);
				order.setOdrFirstSysRate(odrFirstSysRate);
			}

			//系统首付金额
			BigDecimal odrFirstSysMoney = vehSysPrice.multiply(BigDecimal.valueOf(vehCount)).subtract(odrLoanSys).setScale(2, BigDecimal.ROUND_HALF_UP);
			order.setOdrFirstSysMoney(odrFirstSysMoney);


			//服务费
			BigDecimal odrServiceCharge = odrLoanCust.multiply(odrProfitRate).add(odrMortgageFee).multiply(BigDecimal.valueOf(vehCount));
			order.setOdrServiceCharge(odrServiceCharge.setScale(2,BigDecimal.ROUND_HALF_UP));
			//打款金额
			BigDecimal odrPayMoney = (odrLoanSys.subtract((odrMortgageFee.multiply(BigDecimal.valueOf(vehCount))))).multiply((BigDecimal.ONE.subtract(odrProfitRate))).subtract((odrSubsidyCust.multiply(BigDecimal.valueOf(vehCount))));
			order.setOdrPayMoney(odrPayMoney.setScale(2,BigDecimal.ROUND_HALF_UP));

			//公司利润
			BigDecimal odrProfitMoney = (odrLoanCust.multiply(odrProfitRate).add(odrSubsidyCust).subtract(odrSubsidyFac)).multiply(BigDecimal.valueOf(vehCount));
			order.setOdrProfitMoney(odrProfitMoney.setScale(2,BigDecimal.ROUND_HALF_UP));

			//毛利率
			if (odrLoanCust.multiply(BigDecimal.valueOf(vehCount)).compareTo(BigDecimal.ZERO)>0){
				BigDecimal odrGrossRate = odrProfitMoney.divide(odrLoanCust.multiply(BigDecimal.valueOf(vehCount)), 4, BigDecimal.ROUND_HALF_UP);
				order.setOdrGrossRate(odrGrossRate.setScale(4,BigDecimal.ROUND_HALF_UP));
			}

			return R.ok(order);
		}

	}

	@Override
	public OrderVO review(String odrNo) {
		OrderVO orderVO = this.additionalMaterials(odrNo);
		//申请人信息
		orderVO.setApplicant(this.applicant(orderVO.getConCardId()));
		HashMap contactPersonMap = new HashMap<>();
		contactPersonMap.put("relOdrNo",odrNo);
		contactPersonMap.put("relCustUser",orderVO.getOdrCust());
		contactPersonMap.put("relType","Contact");
		orderVO.setContactPersonList(orderRelService.list(contactPersonMap));
		//挂靠公司
		orderVO.setOrderCallDO(this.callCompany(odrNo));
		//实际用车人信息
		UserInfoVO userInfoVO = this.actualUser(String.valueOf(orderVO.getOdrCust()), odrNo);
		userInfoVO.setSpouse(null);
		orderVO.setActualUser(userInfoVO);
		//担保人信息
		HashMap map = new HashMap<>();
		map.put("relOdrNo",odrNo);
		map.put("relCustUser",orderVO.getOdrCust());
		map.put("relType","Guarantee");
		orderVO.setGuarantorList(orderRelService.list(map));
		//审核信息
		orderVO.setActChkRecDOList(flowFeignService.getActChkRecByOdrNo(odrNo));
		//家访信息
		OrderVisitorVO orderVisitorVO = orderVisitorService.getByOdrNo(odrNo);
		//家访图片
		List<OrderVisitImgDO> orderVisitImgDOListImg = new ArrayList<>();
		//家访视频
		OrderVisitImgDO orderVisitImgDOVideo = new OrderVisitImgDO();
		if (orderVisitorVO!=null){
			List<OrderVisitImgDO> orderVisitImgDOList = orderVisitorVO.getOrderVisitImgDOList();
			if (orderVisitImgDOList.size()>0){
				for (OrderVisitImgDO orderVisitImgDO : orderVisitImgDOList) {
					if ("img".equals(orderVisitImgDO.getVimgType())){
						orderVisitImgDOListImg.add(orderVisitImgDO);
					}else if ("video".equals(orderVisitImgDO.getVimgType())){
						orderVisitImgDOVideo = orderVisitImgDO;
					}
				}
			}else {
				orderVisitImgDOList.add(new OrderVisitImgDO());
			}
		}
		if (orderVisitImgDOListImg.size()<=0){
			orderVisitImgDOListImg.add(new OrderVisitImgDO());
		}

		if (orderVisitorVO!=null){
			orderVisitorVO.setOrderVisitDOListImg(orderVisitImgDOListImg);
			orderVisitorVO.setOrderVisitDOVideo(orderVisitImgDOVideo);
			orderVisitorVO.setOrderVisitImgDOList(null);
			orderVO.setOrderVisitorVO(orderVisitorVO);
		}else {
			OrderVisitorVO orderVisitorVO1 = new OrderVisitorVO();
			orderVisitorVO1.setOrderVisitDOListImg(orderVisitImgDOListImg);
			orderVisitorVO1.setOrderVisitDOVideo(orderVisitImgDOVideo);
			orderVO.setOrderVisitorVO(orderVisitorVO1);
		}
		//合同数据
		List<OdrFileCategoryVO> odrFileCategory = new ArrayList<>();
		List<OdrFileInfoVO> odrFileInfoList = new ArrayList<>();
		odrFileInfoList.add(new OdrFileInfoVO());
		odrFileCategory = odrFileCategoryService.getOdrFileCategory();
		if (odrFileCategory.size()>0){
			for (OdrFileCategoryVO odrFileCategoryVO : odrFileCategory) {
				if (odrFileCategoryVO.getOdrFileInfoDOList().size()==0){
					odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoList);
				}else {
					List<OdrFileInfoVO> odrFileInfoDOS = new ArrayList<>();
					odrFileInfoDOS = odrFileCategoryService.contractData(odrNo, odrFileCategoryVO.getCatId());
					//判断是否已经邮寄合同
					for (OdrFileInfoVO odrFileInfoDO : odrFileInfoDOS) {
						OrderMailFileDO byFileId = orderMailFileService.getByFileId(odrNo, odrFileInfoDO.getOfiId());
						if (byFileId!=null){
							odrFileInfoDO.setSelected(true);
						}
					}
					if (odrFileInfoDOS.size()>0){
						odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoDOS);
					}else {
						odrFileInfoDOS.add(new OdrFileInfoVO());
						odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoDOS);
					}
				}
			}
		}else {
			OdrFileCategoryVO odrFileCategoryVO = new OdrFileCategoryVO();
			odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoList);
			odrFileCategory.add(odrFileCategoryVO);
		}
		orderVO.setOdrFileCategoryVOList(odrFileCategory);
		//邮寄合同信息
		OrderMailDO orderMailDO = orderMailService.getByMailOdr(odrNo);
		if (orderMailDO!=null){
			orderVO.setOrderMailDO(orderMailDO);
		}else {
			orderVO.setOrderMailDO(new OrderMailDO());
		}

		//权证信息
		List<OdrFileCategoryVO> warrantList = new ArrayList<>();
		List<OdrFileInfoVO> odrFileInfoLists = new ArrayList<>();
		odrFileInfoLists.add(new OdrFileInfoVO());
		odrFileCategory = odrFileCategoryService.getWarrant();
		if (odrFileCategory.size()>0){
			for (OdrFileCategoryVO odrFileCategoryVO : odrFileCategory) {
				if (odrFileCategoryVO.getOdrFileInfoDOList().size()==0){
					odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoLists);
				}else {
					List<OdrFileInfoVO> odrFileInfoDOS = new ArrayList<>();
					odrFileInfoDOS = odrFileCategoryService.contractData(odrNo, odrFileCategoryVO.getCatId());
					if (odrFileInfoDOS.size()>0){
						odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoDOS);
					}else {
						odrFileInfoDOS.add(new OdrFileInfoVO());
						odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoDOS);
					}
				}
			}
		}else {
			OdrFileCategoryVO odrFileCategoryVO = new OdrFileCategoryVO();
			odrFileCategoryVO.setOdrFileInfoDOList(odrFileInfoLists);
			odrFileCategory.add(odrFileCategoryVO);
		}
		orderVO.setWarrantInformationList(odrFileCategory);
		return orderVO;
	}

	@Override
	public synchronized void downloadAgreement(String odrNo, HttpServletResponse response, HttpServletRequest request, String temType) throws IOException {
		/*if ("docx".equals(temType)){
			XWPFTemplate template = null;
			OutputStream out = null;
			BufferedOutputStream bos = null;
			PayOrderDO payOrderDO = this.get(poId, 1);
			String poInvestor = payOrderDO.getPoInvestor();
			String poOrg = payOrderDO.getPoOrg();
			String orgName = orgService.get(Integer.valueOf(poOrg)).getOrgName();
			try {
				String fileName ;
				Map<String, Object> datas = new HashMap<String, Object>(){{
					put("客户姓名", payOrderDO.getPoCust());
					put("经销名字", orgName);
					put("车辆数量", payOrderDO.getPoVehCount());
					put("打款账户姓名", payOrderDO.getPoName());
					put("打款账户开户行", payOrderDO.getPoBankBranch());
					put("打款账户银行账户", payOrderDO.getPoBankcard());
					put("月租", payOrderDO.getPoMonthRepay().stripTrailingZeros().toPlainString());
					put("融资期限", payOrderDO.getPoLoanIssue());
					put("月租融资期限", payOrderDO.getPoMonthRepay().multiply(BigDecimal.valueOf(payOrderDO.getPoLoanIssue())));
					put("融资服务费", BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoServiceCharge()));
					put("客户超额贴息", BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust()));
					put("融资服务费客户超额贴息", BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust().add(payOrderDO.getPoServiceCharge())));
				}};
//			if ("光大".equals(poInvestor)){
//				//如果未使用插件
//				template = XWPFTemplate.compile("src/main/resources/temp/gdxys.docx").render(datas);
//				fileName = payOrderDO.getPoCust()+"-"+"光大协议书.docx";
//			}else {
//				//如果未使用插件
//				template = XWPFTemplate.compile("src/main/resources/temp/zcxys.docx").render(datas);
//				fileName = payOrderDO.getPoCust()+"-"+"中车协议书.docx";
//			}

				if ("光大".equals(poInvestor)){
					//如果未使用插件
					//获取光大模板路径
					String guangDaTempPath = PropertiesUtils.getKey("tem_guangda");
					System.out.println("############### 光大模板路径：" + guangDaTempPath);
					template = XWPFTemplate.compile(guangDaTempPath).render(datas);
					//template = XWPFTemplate.compile("src/main/resources/temp/gdxys.docx").render(datas);
					fileName = payOrderDO.getPoCust()+"-"+"光大协议书.docx";
				}else {
					//如果未使用插件
					//获取中车模块路径
					String zhogncheTempPath = PropertiesUtils.getKey("tem_zhongchen");
					System.out.println("############### 中车模板路径：" + zhogncheTempPath);
					template = XWPFTemplate.compile(zhogncheTempPath).render(datas);
					//template = XWPFTemplate.compile("src/main/resources/temp/zcxys.docx").render(datas);
					fileName = payOrderDO.getPoCust()+"-"+"中车协议书.docx";
				}
				response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//			String agent = request.getHeader("User-Agent");
//			boolean isMSIE =((agent!=null&& agent.contains("MSIE"))||(agent!=null&& agent.contains("like Gecko")));
//			if(isMSIE){
//				response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF8"));
//			}else{
				response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
//			}
				out = response.getOutputStream();
				bos = new BufferedOutputStream(out);
				template.write(out);
			} catch (IOException e) {
				e.printStackTrace();
				return R.error();
			} finally {
				assert template != null;
				template.close();
				assert bos != null;
				bos.flush();
				bos.close();
				out.flush();
				out.close();
			}
			return R.ok();
		}else {*/
		if ("gmht".equals(temType)){
			String fileName ;
			String fileTemplate;
			Map<String, Object> mapJson = new HashMap<>();
			OrderDO orderDO = this.get(odrNo);

			/*mapJson.put("poCust",payOrderDO.getPoCust());
			mapJson.put("orgName",orgName);
			mapJson.put("poVehCount",payOrderDO.getPoVehCount());
			mapJson.put("bcName",payOrderDO.getPoName());
			mapJson.put("bcBank",payOrderDO.getPoBankBranch());
			mapJson.put("bcNo",payOrderDO.getPoBankcard());
			mapJson.put("yuezu",payOrderDO.getPoMonthRepay().stripTrailingZeros().toPlainString());
			mapJson.put("poLoanIssue",payOrderDO.getPoLoanIssue());
			mapJson.put("heji",payOrderDO.getPoMonthRepay().multiply(BigDecimal.valueOf(payOrderDO.getPoLoanIssue())));
			mapJson.put("fuwufei",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoServiceCharge()));
			mapJson.put("khcetx",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust()));
			mapJson.put("hj",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust().add(payOrderDO.getPoServiceCharge())));*/
			response.reset();
			response.setCharacterEncoding("UTF-8");

			fileName = "购买合同.pdf";

			// 定义输出类型
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));

			try {
				ServletOutputStream out = response.getOutputStream();
				PdfUtil pdf = new PdfUtil();
				fileTemplate = Constant.tem_gmht;//读取项目中模板位置
				System.out.println("文件路径----------------"+fileTemplate);
				pdf.fillTemplate(mapJson ,out,fileTemplate);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("成功导出pdf");
		}else if ("qrs".equals(temType)){
			String fileName ;
			String fileTemplate;
			Map<String, Object> mapJson = new HashMap<>();
			OrderDO orderDO = this.get(odrNo);

			/*mapJson.put("poCust",payOrderDO.getPoCust());
			mapJson.put("orgName",orgName);
			mapJson.put("poVehCount",payOrderDO.getPoVehCount());
			mapJson.put("bcName",payOrderDO.getPoName());
			mapJson.put("bcBank",payOrderDO.getPoBankBranch());
			mapJson.put("bcNo",payOrderDO.getPoBankcard());
			mapJson.put("yuezu",payOrderDO.getPoMonthRepay().stripTrailingZeros().toPlainString());
			mapJson.put("poLoanIssue",payOrderDO.getPoLoanIssue());
			mapJson.put("heji",payOrderDO.getPoMonthRepay().multiply(BigDecimal.valueOf(payOrderDO.getPoLoanIssue())));
			mapJson.put("fuwufei",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoServiceCharge()));
			mapJson.put("khcetx",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust()));
			mapJson.put("hj",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust().add(payOrderDO.getPoServiceCharge())));*/
			response.reset();
			response.setCharacterEncoding("UTF-8");

			fileName = "确认书.pdf";

			// 定义输出类型
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));

			try {
				ServletOutputStream out = response.getOutputStream();
				PdfUtil pdf = new PdfUtil();
				fileTemplate = Constant.tem_qrs;//读取项目中模板位置
				System.out.println("文件路径----------------"+fileTemplate);
				pdf.fillTemplate(mapJson ,out,fileTemplate);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("成功导出pdf");
		}else if ("xys".equals(temType)){
			String fileName ;
			String fileTemplate;
			Map<String, Object> mapJson = new HashMap<>();
			OrderDO orderDO = this.get(odrNo);

			/*mapJson.put("poCust",payOrderDO.getPoCust());
			mapJson.put("orgName",orgName);
			mapJson.put("poVehCount",payOrderDO.getPoVehCount());
			mapJson.put("bcName",payOrderDO.getPoName());
			mapJson.put("bcBank",payOrderDO.getPoBankBranch());
			mapJson.put("bcNo",payOrderDO.getPoBankcard());
			mapJson.put("yuezu",payOrderDO.getPoMonthRepay().stripTrailingZeros().toPlainString());
			mapJson.put("poLoanIssue",payOrderDO.getPoLoanIssue());
			mapJson.put("heji",payOrderDO.getPoMonthRepay().multiply(BigDecimal.valueOf(payOrderDO.getPoLoanIssue())));
			mapJson.put("fuwufei",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoServiceCharge()));
			mapJson.put("khcetx",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust()));
			mapJson.put("hj",BigDecimalUtil.number2CNMontrayUnit(payOrderDO.getPoSubsidyCust().add(payOrderDO.getPoServiceCharge())));*/
			response.reset();
			response.setCharacterEncoding("UTF-8");

			fileName = "协议书.pdf";

			// 定义输出类型
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));

			try {
				ServletOutputStream out = response.getOutputStream();
				PdfUtil pdf = new PdfUtil();
				fileTemplate = Constant.tem_xys;//读取项目中模板位置
				System.out.println("文件路径----------------"+fileTemplate);
				pdf.fillTemplate(mapJson ,out,fileTemplate);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("成功导出pdf");
		}

//		}
	}

	/**
	 * @Author Zhn
	 * @Description //TODO 回款确认列表
	 * @Date 15:45 2021/5/28
	 * @Param [单号，姓名]
	 * @return com.bdzl.pub.entity.sys.OrgDO
	 **/
	@Override
	public List<PaymentVO> paymentList(Map<String,Object> map) {
		return orderDao.paymentList(map);
	}


	@Override
	public ContractOnlineSignrecVO getContractByUser(String odrNo, String signer) {
		return orderDao.getContractByUser(odrNo,signer);
	}



	/**
	 * todo 订单统计
	 */
	@Override
	public List<OrderVO> statisticsOrderList(Map map){
		return orderDao.statisticsOrderList(map);
	}
	@Override
	public Integer statisticsOrderListcount(Map map){
		return orderDao.statisticsOrderListcount(map);
	}

	@Override
	public List<String> getRoleByUserId(Integer userId) {
		return orderDao.getRoleByUserId(userId);
	}

	@Override
	public List<String> getStatValByRole(List<String> roleIds) {
		return orderDao.getStatValByRole(roleIds);
	}

	/**
	 * @Author Zhn
	 * @Description //TODO 获取打款金额
	 * @Date 11:43 2021/5/29
	 * @Param [month,today] 传month = 任意值 获取当前月  传today = 任意值 获取当前日    禁止同时传值
	 * @return com.bdzl.pub.vo.loan.OrderVO
	 **/
	@Override
	public BigDecimal sumOdrPayMoney(Map<String,Object> map) {
		return orderDao.sumOdrPayMoney(map);
	}

	/**
	 * @Author Zhn
	 * @Description //TODO 获取融资金额
	 * @Date 11:43 2021/5/29
	 * @Param [month,today] 传month = 任意值 获取当前月  传today = 任意值 获取当前日    禁止同时传值
	 * @return com.bdzl.pub.vo.loan.OrderVO
	 **/
	@Override
	public BigDecimal sumOdrLoanSys(Map<String,Object> map) {
		return orderDao.sumOdrLoanSys(map);
	}



	@Override
	public ActNodeNextDO getByNowAndNext(Integer nowId, Integer nextId) {
		return orderDao.getByNowAndNext(nowId,nextId);
	}


	/**
	 *订单统计，订单总额
	 * @param map
	 * @return {
	 * 融资总额，sumOdrLoanSys
	 * 返佣总额，sumOdrReturnMoney
	 * 奖励总额，sumOdrBonusMoney
	 * 打款总额，sumOdrPayMoney
	 * 利润总额，sumOdrProfitMoney
	 * 平均毛利率，avgOdrGrossRate }
	 */
	@Override
	public Map<String,String> statisticsOrderSumPrice(Map map){
		return orderDao.statisticsOrderSumPrice(map);
	}

	/**
	 * 订单统计页面
	 * @param map
	 * @return{
	 * 融资总额，sumOdrLoanSys
	 * 放款总额，sumodrPayMoney
	 * 订单数量，orderCount}
	 */
	@Override
	public Map<String, String> statisticsOrderCount(Map map){
		return orderDao.statisticsOrderCount(map);
	}
}
